package codepulse.blogmoon.cn.system.service.impl;

import codepulse.blogmoon.cn.common.context.Context;
import codepulse.blogmoon.cn.common.utils.BaseConvert;
import codepulse.blogmoon.cn.system.dto.CreateTeamDTO;
import codepulse.blogmoon.cn.system.dto.TeamInfoDTO;
import codepulse.blogmoon.cn.system.entity.TeamAcctRel;
import codepulse.blogmoon.cn.system.service.TeamAcctRelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import codepulse.blogmoon.cn.system.entity.TeamInfo;
import codepulse.blogmoon.cn.system.service.TeamInfoService;
import codepulse.blogmoon.cn.system.mapper.TeamInfoMapper;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.assertj.core.util.Sets;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 61748
 * @description 针对表【team_info】的数据库操作Service实现
 * @createDate 2024-01-29 11:33:05
 */
@Service
public class TeamInfoServiceImpl extends ServiceImpl<TeamInfoMapper, TeamInfo>
        implements TeamInfoService {

    @Resource
    private TeamAcctRelService teamAcctRelService;

    @Override
    @Transactional
    public void createTeam(CreateTeamDTO dto) {
        TeamInfo teamInfo = BaseConvert.convert(dto, TeamInfo.class);
        teamInfo.setCreateField();
        save(teamInfo);

        Set<Long> acctRelSet = Sets.newHashSet();
        acctRelSet.add(Context.get().getBizAcctId());
        if (CollectionUtils.isNotEmpty(dto.getTeamAcctIdList())) {
            acctRelSet.addAll(dto.getTeamAcctIdList());
        }
        List<TeamAcctRel> teamAcctRelList = acctRelSet.stream().map(item -> {
            TeamAcctRel teamAcctRel = new TeamAcctRel();
            teamAcctRel.setTeamId(teamInfo.getId());
            teamAcctRel.setBizAcctId(item);
            return teamAcctRel;
        }).collect(Collectors.toList());
        teamAcctRelService.saveBatch(teamAcctRelList);
    }

    @Override
    public List<TeamInfoDTO> listSelfTeam(Long bizAccountId) {
        List<TeamInfo> teamInfoList = baseMapper.selectTeamByAcctId(bizAccountId);
        return BaseConvert.convertList(teamInfoList, TeamInfoDTO.class);
    }
}




